package site.guns.service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import site.guns.couchdb.GunsDb;
import site.guns.domain.GunInfo;

import com.ning.http.client.AsyncHttpClient;

@Service
public class PriceUpdater {
    @Autowired
    private GunsDb gunsDb;

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private AsyncHttpClient httpClient;

    @Scheduled(cron = "0 0 3 * * *")
    public void updatePrices() {
        for (GunInfo info : gunsDb.getBuiltInView().<GunInfo>createDocsQuery().asDocs()) {
            try {
                String body = httpClient.prepareGet(info.getShopLink()).execute().get().getResponseBody("cp1251");

                int index = body.indexOf("src=\"images/add.jpg\"");

                Pattern p = Pattern.compile("(\\d+) руб.");

                Matcher m = p.matcher(body.substring(index - 300, index));

                if (m.find()) {
                    int price = Integer.parseInt(m.group(1));

                    if (price > 1) {
                        info.setPrice(price);

                        gunsDb.saveOrUpdate(info);

                        logger.info("Обновление цены для товара: " + info.getName() + " : " + price + " руб.");
                    } else {
                        throw new IllegalStateException("Возможно товара нет в наличии: " + info.getShopLink());
                    }
                } else {
                    throw new IllegalStateException("Цена для товара не найдена: " + info.getShopLink());
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }
}
